const [user, setUser] = React.useState(null);
const [token, setToken] = React.useState(null);
const [error, setError] = React.useState('');
async function login(user = null){ // default user to null
TodoDataService.login(user)
.then(response =>{
setToken(response.data.token);
setUser(user.username);
localStorage.setItem('token', response.data.token);
localStorage.setItem('user', user.username);
setError('');
})
.catch( e =>{
console.log('login', e);
setError(e.toString());
});
}
* Contact [email protected] for the source code if you prefer to copy and paste
Code Explanation
Analyze Code
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
Our simple login form consists of a username and password fields. We use the React useState hook to create the
username and password state variables. The username and password state variables keep track of what a user has
entered into the login form fields. username and password are default set to empty strings with useState(“”).
Analyze Code
<Form.Group className="mb-3">
<Form.Label>Username</Form.Label>
<Form.Control
type="text"
placeholder="Enter username"
value={username}
onChange={onChangeUsername}
/>
</Form.Group>
In the username FormControl (in the Form JSX Markup), we set the field’s value to the username state variable. So
this field will always reflect the value in username. We set onChange to onChangeUsername, so any value changes
done by the user entering in the field will call onChangeUsername which will in turn update username state
variable. In essence, we have double binded username field to the username state. The password FormControl
works similarly.
Analyze Code
const login = () => {
props.login({username: username, password: password});
props.history.push('/');
}
When we click on the Login button, it calls login. Notice that we call props.login. But who passes this login
function into the Login component? If you recall in App.js, we have the following route:
Analyze Code
<Route path="/login" render={(props)=>
<Login {...props} login={login} />
}>
</Route>
And login is defined in App.js as:
Analyze Code
async function login(user = null){ // default user to null
TodoDataService.login(user)
.then(response =>{
setToken(response.data.token);
setUser(user.username);
localStorage.setItem('token', response.data.token);
localStorage.setItem('user', user.username);
setError('');
})
.catch( e =>{
console.log('login', e);